<template>
    <div id="version-diff-compare">
        <div class="head">
            <h1 class="title">静态比对</h1>
        </div>
        <div class="content">
            <div class="top-content">
                <div :class="['top-content-result', 'flex-layout']">
                    <i :class="resultIcon"></i>
                    <span class="fontS16">
                        {{ resultTitle }}
                    </span>
                    <div class="top-content-stastic">
                        <span>涉及条目数:{{ showNumberValue(recordInfo.compareEntryCount) }}</span>
                        <span>涉及产品数:{{ showNumberValue(recordInfo.compareFundCount) }}</span>
                        <span>
                            数据量:{{ showNumberValue(recordInfo.compareResultCount) }}
                            <span class="same"> (一致数:{{ showNumberValue(recordInfo.sameResultCount) }}</span>
                            <span class="diff">不一致数:{{ showNumberValue(recordInfo.diffResultCount) }})</span>
                        </span>
                    </div>
                </div>
                <div :class="['top-content-finish', 'flex-layout']">
                    <i :class="finishIcon"></i>
                    <span class="fontS16">
                        {{ finishTitle }}
                    </span>
                    <el-button type="primary" size="mini" @click="handleBtn('compare')" :disabled="recordInfo.compareStatuts === '1'"
                        >重新比对</el-button
                    >
                </div>
            </div>
            <el-divider></el-divider>
            <div class="table-content">
                <div class="table-operate">
                    <el-checkbox v-model="showDiffData" @change="changeShowDiffData(true)">
                        <span>比对结果不一致</span>
                    </el-checkbox>
                    <el-button @click="handleBtn('loadout')" size="mini" type="primary" style="margin-left: 5px" :loading="loadOutLoading"
                        >导出</el-button
                    >
                </div>
                <div class="table-detail">
                    <el-tabs type="card" v-model="editableTabsValue">
                        <el-tab-pane label="比对结果明细" name="detail">
                            <RiskTableP
                                ref="risk-table"
                                :tableConfig="tableConfig"
                                :tableData="tableData"
                                :column="tableColumns"
                                :paging="paging"
                                :searchParams="searchParams"
                                v-loading="tableLoading"
                                :contentHeight="'calc(100% - 32px)'"
                                :defaultSort="{ field: 'entryCode', order: 'asc' }"
                                @page-change="pageChange"
                                :key="'tableKey' + tableKey"
                            >
                                <template #fundCodes-slot="{ $panel, column }">
                                    <RiskEntryInput
                                        class="my-select"
                                        @set-entry-data="
                                            value => {
                                                option.data = value;
                                                $panel.changeOption($event, !!option.data, option);
                                            }
                                        "
                                        :returnDatas="option.data"
                                        v-for="(option, index) in column.filters"
                                        :key="index"
                                    />
                                </template>
                                <template #stockCodes-slot="{ $panel, column }">
                                    <RiskEntryInputPlus
                                        class="my-select"
                                        :requestParams="{
                                            url: '/static/difference/stock/select',
                                            method: 'post',
                                            data: {},
                                            filterValue: 'dictKey',
                                        }"
                                        @set-entry-data="
                                            value => {
                                                option.data = value;
                                                $panel.changeOption($event, !!option.data, option);
                                            }
                                        "
                                        :returnDatas="option.data"
                                        v-for="(option, index) in column.filters"
                                        :key="index"
                                    />
                                </template>
                                <template #stockCodes="scope">
                                    <el-tag v-if="scope.row.stockCodeCount > 1" style="cursor: default">
                                        <el-popover
                                            :ref="'dcPopover' + scope.row.entryKey"
                                            trigger="hover"
                                            popper-class="tips-popper"
                                            :open-delay="500"
                                            @show="getPopInfo(scope.row)"
                                            @after-leave="hideSingle"
                                        >
                                            <span v-if="!popKeyInfo.stockNames">加载中...</span>
                                            <div v-for="item in popKeyInfo.stockNames" :key="item.dictKey">
                                                {{ item.dictKey + getShowKeyName(item.dictKeyName) }}
                                            </div>
                                            <div slot="reference">
                                                <span> {{ scope.row.stockCodeCount + '个证券' }} </span>
                                            </div>
                                        </el-popover>
                                    </el-tag>
                                    <span v-else-if="scope.row.hasOwnProperty('stockNames') && scope.row.stockCodeCount === 1">
                                        {{ scope.row.stockNames[0].dictKey + ' ' + getShowKeyName(scope.row.stockNames[0].dictKeyName) }}
                                    </span>
                                    <span v-else> -- </span>
                                </template>

                                <template #fundCodes="scope">
                                    <!-- 换种方式或者key重新渲染 -->
                                    <el-tag v-if="scope.row.fundCodeCount > 1" style="cursor: default">
                                        <el-popover
                                            :ref="'dcPopover' + scope.row.entryKey"
                                            trigger="hover"
                                            popper-class="tips-popper"
                                            :open-delay="500"
                                            @show="getPopInfo(scope.row)"
                                            @after-leave="hideSingle"
                                        >
                                            <span v-if="!popKeyInfo.fundNames">加载中...</span>
                                            <div v-for="item in popKeyInfo.fundNames" :key="item.dictKey">
                                                {{ item.dictKey + ' ' + getShowKeyName(item.dictKeyName) }}
                                            </div>
                                            <div slot="reference">
                                                <span>{{ scope.row.fundCodeCount + '个产品' }}</span>
                                            </div>
                                        </el-popover>
                                    </el-tag>
                                    <span v-else-if="scope.row.hasOwnProperty('fundNames') && scope.row.fundCodeCount === 1">
                                        {{ scope.row.fundNames[0].dictKey + ' ' + getShowKeyName(scope.row.fundNames[0].dictKeyName) }}
                                    </span>
                                    <span v-else> -- </span>
                                </template>
                            </RiskTableP>
                            <div class="rules">
                                <span> 操作规则 </span>
                                <el-tooltip placement="bottom" effect="light" popper-class="first-tooltip-content">
                                    <div slot="content">
                                        <span>"系统升级前后静态结果比对"操作规范:</span>
                                        <span> ①系统升级前，进行静态风险计算(不进行导数)；</span>
                                        <span> ②将静态计算结果进行备份； </span>
                                        <span> ③系统升级后，再次进行静态风险计算(不进行导数)； </span>
                                        <span> ④比较两次的计算结果值是否一致。</span>
                                    </div>
                                    <i class="el-icon-question"></i>
                                </el-tooltip>
                                <span> 计算时间 </span>
                                <el-tooltip placement="bottom" effect="light" popper-class="tooltip-content">
                                    <div slot="content">
                                        <span>升级前静态计算时间：{{ showNumberValue(recordInfo.beforeCalDateTime) }}</span>
                                        <span>升级后静态计算时间：{{ showNumberValue(recordInfo.afterCalDateTime) }}</span>
                                        <span>静态结果比对时间：{{ showNumberValue(recordInfo.compareDateTime) }}</span>
                                    </div>
                                    <i class="el-icon-question"></i>
                                </el-tooltip>
                                <span> 数据量 </span>
                                <el-tooltip placement="bottom" effect="light" popper-class="tooltip-content">
                                    <div slot="content">
                                        <span>升级前静态计算数据量：{{ showNumberValue(recordInfo.beforeResultCount) }}</span>
                                        <span>升级后静态计算数据量：{{ showNumberValue(recordInfo.afterResultCount) }}</span>
                                        <span>静态结果比对数据量：{{ showNumberValue(recordInfo.compareResultCount) }} </span>
                                    </div>
                                    <i class="el-icon-question"></i>
                                </el-tooltip>
                                <span> 涉及条目数 </span>
                                <el-tooltip placement="bottom" effect="light" popper-class="tooltip-content">
                                    <div slot="content">
                                        <span>升级前静态计算涉及条目数：{{ showNumberValue(recordInfo.beforeEntryCount) }}</span>
                                        <span>升级后静态计算涉及条目数：{{ showNumberValue(recordInfo.afterEntryCount) }}</span>
                                        <span>静态结果比对涉及条目数：{{ showNumberValue(recordInfo.compareEntryCount) }}</span>
                                    </div>
                                    <i class="el-icon-question"></i>
                                </el-tooltip>
                                <span> 涉及产品数 </span>
                                <el-tooltip placement="bottom" effect="light" popper-class="tooltip-content">
                                    <div slot="content">
                                        <span>升级前静态计算涉及产品数：{{ showNumberValue(recordInfo.beforeFundCount) }}</span>
                                        <span>升级后静态计算涉及产品数：{{ showNumberValue(recordInfo.afterFundCount) }}</span>
                                        <span>静态结果比对涉及产品数：{{ showNumberValue(recordInfo.compareFundCount) }}</span>
                                    </div>
                                    <i class="el-icon-question"></i>
                                </el-tooltip>
                            </div>
                        </el-tab-pane>
                    </el-tabs>
                </div>
            </div>
        </div>
    </div>
</template>

<script lang="ts">
import RiskEntryInputPlus from '@/common/components/risk-entry-input-plus.vue';
import RiskEntryInput from '@/common/components/risk-entry-input.vue';
import RiskTableP from '@/common/components/risk-table-plus.vue';
import { TableConfigVO } from '@/common/vo';
import { downLoadFile } from '@/utils/request';
import { Vue, Component } from 'vue-property-decorator';
import * as api from './api/version-diff-compare';
@Component({
    name: 'VersionDiffCompare',
    components: { RiskTableP, RiskEntryInput, RiskEntryInputPlus },
})
export default class VersionDiffCompare extends Vue {
    searchParams: any = {
        consistentList: ['1'],
        sort: {
            field: 'entryCode',
            order: 'asc',
            // sortSql: '',
            // advancedSort: {},
        },
    };
    private popInfoStorage: any = {}; // 证券集合仓库(枚举)
    popKeyInfo: any = {}; // 显示的浮窗数据
    editableTabsValue: string = 'detail';
    showDiffData: boolean = true;
    recordInfo: any = {
        compareEntryCount: 0,
        compareFundCount: 0,
        compareResultCount: 0,
        sameResultCount: 0,
        diffResultCount: 0,
        compareResultStatuts: '',
        compareStatuts: '0',
    };

    tableConfig: TableConfigVO = {
        rowKey: 'entryCode', // 主键key
        allRowKeys: [], // 所有页数据的key集合
    };
    tableData: any = [];
    paging: any = {
        currentPage: 1,
        pageSize: 25,
        total: 0,
    };
    isConsistentList: any = [
        { label: '一致', value: '0', checked: false },
        { label: '不一致', value: '1', checked: true },
    ];
    tableColumns: any = [
        {
            title: '条目编号',
            field: 'entryCode',
            filterType: 'search',
            search: true,
            sortable: true,
            filters: [{ data: '' }],
        },
        {
            title: '产品',
            field: 'fundCodes',
            filterType: 'search',
            search: true,
            sortable: true,
            filters: [{ data: '' }],
            filterField: 'fundCode',
            align: 'center',
        },
        {
            title: '证券',
            field: 'stockCodes',
            filterType: 'search',
            search: true,
            minWidth: '150',
            sortable: true,
            filters: [{ data: '' }],
            filterField: 'stockCode',
            align: 'center',
        },
        {
            title: '是否一致',
            field: 'consistent',
            filterType: 'funnel',
            search: true,
            minWidth: '150',
            sortable: true,
            filters: this.isConsistentList,
            filterField: 'consistentList',
            style: value => {
                if (value == '1') {
                    return { color: '#fd6b6d' };
                } else if (value == '0') {
                    return { color: '#409eff' };
                }
            },
            render: value => this.isConsistentList.find(item => item.value == value)?.label || '--',
            align: 'center',
        },
        {
            title: '计算结果(升级前)',
            field: 'beforeResult',
            search: true,
            minWidth: '150',
            sortable: true,
            render: value => value || '--',
            align: 'center',
        },
        {
            title: '计算结果(升级后)',
            field: 'afterResult',
            search: true,
            minWidth: '150',
            sortable: true,
            render: value => value || '--',
            align: 'center',
        },
    ];
    tableKey: number = 0;
    tableLoading: boolean = false;
    loadOutLoading: boolean = false;
    timeInter = null;
    get resultIcon() {
        // 对比结果状态 0 完全匹配 1 不完全匹配  TODO 未比对图标处理
        const cStatuts = this.recordInfo.compareStatuts;
        const status = this.recordInfo.compareResultStatuts;
        // 比对中
        if (cStatuts == '1') {
            return ['el-icon-more', 'icon-more'];
        } else if (status == '0') {
            return ['el-icon-success', 'icon-success'];
        } else if (status === '1') {
            return ['el-icon-error', 'icon-error'];
        }
    }

    get resultTitle() {
        // 对比结果状态 0 完全匹配 1 不完全匹配 未比对图标处理
        const cStatuts = this.recordInfo.compareStatuts;
        const status = this.recordInfo.compareResultStatuts;
        if (cStatuts == '1') {
            return '加载中';
        } else if (status == '0') {
            return '完全匹配！';
        } else if (status === '1') {
            return '不完全匹配！';
        } else {
            return '未比对';
        }
    }

    get finishIcon() {
        //  0 未对比 1 对比中 2 对比完成 3 比对失败
        const status = this.recordInfo.compareStatuts;
        if (status == '0') {
            return '未比对';
        } else if (status == '1') {
            return ['el-icon-loading', 'icon-loading'];
        } else if (status == '2' || status === '3') {
            return ['el-icon-success', 'icon-finish'];
        }
    }

    get finishTitle() {
        //  0 未对比 1 对比中 2 对比完成 3 比对失败
        const status = this.recordInfo.compareStatuts;
        if (status == '0') {
            return '未比对';
        } else if (status == '1') {
            return '比对中...';
        } else if (status == '2' || status === '3') {
            return '比对完成！';
        }
    }

    async mounted() {
        let status: any = await this.getRecordInfo();
        console.log(status, '-------------');

        if (status === '0') {
            return;
        }
        if (status === '1') {
            // 比对中
            this.setInter();
        }
        this.getTableData();
    }

    /**
     * 勾选是否展示比对结果不一致
     */
    changeShowDiffData(updateTable?: boolean) {
        const $table = this.$refs['risk-table'] as any;
        const $xTable = $table.$refs['xTable'];
        const column = $xTable.getColumnByField('consistent');
        let consistentList = [];
        if (column) {
            $xTable.setFilter(
                column,
                column.filters.map(ele => {
                    if (ele.value == '1') {
                        ele.checked = this.showDiffData;
                    } else {
                        ele.checked = false;
                    }
                    ele.checked && consistentList.push(ele.value);
                    return ele;
                })
            );

            this.searchParams.consistentList = consistentList;
            // 修改条件之后，需要手动调用 updateData 处理表格数据
            $xTable.updateData();
        }

        updateTable && this.getTableData();
    }

    /**
     * 获取表格数据
     */
    getTableData() {
        this.tableLoading = true;
        api.staticDiffenceQuery({ ...this.searchParams, paging: this.paging })
            .then((res: any) => {
                // 状态判断
                this.tableData = res.list;
                this.paging.total = res.total;
                this.popInfoStorage = {};
            })
            .catch(err => {
                console.log(err, 'staticDiffenceQuery');
            })
            .finally(() => {
                this.tableLoading = false;
            });
    }

    /**
     * 静态比对结果记录查询
     */
    getRecordInfo() {
        return new Promise((resolve, reject) => {
            api.staticDiffenceRecord()
                .then((res: any) => {
                    if (res) {
                        this.recordInfo = res;
                        const compareStatuts = res.compareStatuts;
                        if (compareStatuts == '2' || compareStatuts == '3') {
                            this.beforeDestory();
                        }
                    } else {
                        this.recordInfo = {
                            compareStatuts: '0',
                            compareResultStatuts: '--',
                        };
                    }

                    resolve(res.compareStatuts);
                })
                .catch(err => {
                    console.log('staticDiffenceRecord');
                    resolve(err);
                });
        });
    }

    /**
     * 按钮操作
     */
    async handleBtn(type: string) {
        if (type === 'compare') {
            this.resetRecord();
            api.staticDiffenceCompare().then((res: any) => {
                if (res && JSON.stringify(res) !== '{}') {
                    const compareStatuts = res.compareStatuts;
                    this.recordInfo = res;
                    if (compareStatuts == '1') {
                        this.recordInfo = {
                            compareResultStatuts: res.compareResultStatuts,
                            compareStatuts: res.compareStatuts,
                        };
                        // 比对中
                        this.setInter();
                    } else {
                        this.getTableData();
                    }
                }
            });
        } else if (type === 'loadout') {
            this.loadOutLoading = true;
            await downLoadFile({
                url: '/static/difference/export',
                method: 'post',
                data: { ...this.searchParams, paging: this.paging },
            });
            this.loadOutLoading = false;
        }
    }
    /**
     * 重置记录
     */
    resetRecord() {
        // const $Table = this.$refs['risk-table'] as any;
        // console.log($Table, '$Table');
        // const $xTable = $Table?.$refs['xTable'];
        // ($xTable as any).clearFilter();
        // ($xTable as any).clearSort();
        this.tableData = [];
        this.paging.total = 0;
        this.paging.currentPage = 1;
        this.searchParams = {
            consistentList: ['1'],
            sort: { field: 'entryCode', order: 'asc' },
        };
        this.tableKey++;
        this.showDiffData = true;
        this.changeShowDiffData(false);

        this.recordInfo = {
            compareStatuts: '0',
            compareResultStatuts: '--',
        };
    }
    /**
     * 分页、筛选
     */
    pageChange($event?: any) {
        if ($event && $event.type == 'sort') {
            this.searchParams.sort = {
                field: $event['sortField'],
                order: $event['order'],
            };
        }
        this.getTableData();
    }
    /**
     * 设置定时器
     */
    setInter() {
        this.beforeDestory();
        this.timeInter = setInterval(() => {
            this.getRecordInfo();
            this.getTableData();
        }, 60 * 1000);
        // TODO
    }

    /**
     * 产品、证券显示名称处理
     */
    getShowKeyName(value: string) {
        if (value) {
            return `(${value})`;
        } else {
            return '';
        }
    }

    /**
     * 显示数字值
     */
    showNumberValue(value: any) {
        if (value || value === 0) {
            return value;
        } else {
            return '--';
        }
    }

    /**
     * 产品、证券更多信息
     */
    getPopInfo(row: any) {
        const { stockCodeCount, entryKey } = row;
        if (this.popInfoStorage[entryKey]) {
            this.popKeyInfo = this.popInfoStorage[entryKey];
            return;
        }
        if (stockCodeCount < 3) {
            this.popKeyInfo = row;
        } else {
            api.staticDiffenceQueryDetail({ entryKey })
                .then((res: any) => {
                    this.popKeyInfo = res;
                    this.popInfoStorage[entryKey] = res;
                    this.$nextTick(() => {
                        (this.$refs['dcPopover' + entryKey] as any).updatePopper(); // 重新调整popover位置
                    });
                })
                .catch(() => {});
        }
    }

    /**
     * popover弹框隐藏
     */
    hideSingle() {
        setTimeout(() => {
            this.popKeyInfo = {};
        }, 50);
    }

    /**
     * 关闭定时器
     */
    beforeDestory() {
        if (this.timeInter) {
            clearInterval(this.timeInter);
            this.timeInter = null;
        }
    }
}
</script>

<style lang="scss" scoped>
#version-diff-compare {
    width: 100%;
    height: 100%;
    min-width: 1200px;

    .head {
        width: 100%;
        height: 60px;
        background-image: url('./images/title.png');
        background-size: 100%;

        .title {
            font-size: 24px;
            font-weight: 600;
            color: #107fff;
            line-height: 33px;
            letter-spacing: 20px;
            text-align: center;
            height: 100%;
            line-height: 60px;
        }
    }

    .content {
        height: calc(100% - 60px);
        border: 1px solid #d7d7d7;
        .top-content {
            padding: 5px 10px 5px 5px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            .flex-layout {
                display: flex;
                align-items: center;
                justify-content: center;
            }
            .top-content-result {
                .icon-success {
                    font-size: 42px;
                    color: #1296db;
                }
                .icon-error {
                    font-size: 42px;
                    color: #fd6b6d;
                }
                .icon-more {
                    width: 42px;
                    height: 42px;
                    text-align: center;
                    padding-top: 7px;
                    vertical-align: top;
                    background-color: rgb(138, 138, 138);
                    color: #fff;
                    font-size: 26px;
                    border-radius: 50%;
                }
            }

            .top-content-stastic {
                span {
                    margin-left: 10px;
                }
                .same {
                    margin-left: 2px;
                    color: #409eff;
                }
                .diff {
                    color: #fd6b6d;
                }
            }
            .top-content-finish {
                .icon-finish {
                    font-size: 36px;
                    color: #1296db;
                }
                .icon-loading {
                    font-size: 38px;
                    color: #eb9c7a;
                }
            }
            .fontS16 {
                font-size: 16px;
                font-weight: bolder;
                margin: 0px 6px;
            }
        }
        .table-content {
            position: relative;
            //     display: flex;
            height: calc(100% - 57px);
            .table-operate {
                // TODO
                width: 220px;
                position: absolute;
                right: 0;
                z-index: 99;
                margin-right: 5px;
            }
            .table-detail {
                height: 100%;
                /deep/ .el-tabs .el-tabs__nav .el-tabs__item {
                    line-height: 34px;
                    padding: 0 25px;
                    span {
                        border-right: 0px solid #fff;
                    }
                }
                .rules {
                    color: #333;
                    position: absolute;
                    bottom: 7px;
                    span:nth-child(n + 2) {
                        margin-left: 20px;
                    }
                }
            }
        }
    }
}
.tooltip-content {
    span {
        display: block;
        margin: 8px 0;
        &:last-child {
            text-indent: 1em;
        }
    }
}
.first-tooltip-content {
    span {
        display: block;
        margin: 8px 0;
        &:first-child {
            font-weight: bolder;
        }
        &:nth-child(n + 2) {
            text-indent: 10px;
        }
    }
}

/deep/ .el-divider--horizontal {
    margin: 2px 0 !important;
}

/deep/ .el-tabs {
    height: 100%;
    .el-tabs__content {
        padding: 5px 10px;
        height: calc(100% - 40px);
        overflow: auto;
        position: relative;

        .el-tab-pane {
            height: 100%;
        }
    }
}
/deep/ .el-pagination {
    padding: 4px !important;
}
/deep/ .el-checkbox__input.is-checked + .el-checkbox__label {
    color: #575757 !important;
}
/deep/.el-tabs__nav-wrap {
    width: calc(100% - 220px);
}
</style>
<style>
.el-tooltip__popper.is-light {
    background: #f2f2f2 !important;
}
.tips-popper {
    max-width: 700px;
    max-height: 300px;
    overflow: auto;
}
.my-select {
    margin: 5px;
    width: calc(100% - 10px);
}
</style>
